<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>nodejs + socket.io.js聊天室</title>
    <script src="/js/jquery-1.8.3.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <style type="text/css">
        body { font-size: 12px; margin: 10px; }
    </style>
    <script>
        var username, socket, div, online, input;

        function login(username) {
            $('<p><b>' + username + '</b> <em style="color: gray">进入聊天室</em></p>').appendTo(div);
            scroll();
        }

        function logout(username) {
            $('<p><b>' + username + '</b> <em style="color: gray">离开聊天室</em></p>').appendTo(div);
            online.find('#' + username).remove();
            scroll();
        }

        function scroll() {
            div.animate({
                scrollTop: div[0].scrollHeight
            });
        }


        function str_pad(str, length, pad, padType) {
            str = String(str);
            length = length ? length : 10;
            pad = pad == undefined ? ' ' : pad;

            while (str.length < length) {
                str = padType == 'right' ? str + pad : pad + str;
            }

            return str;
        }

        function date(format, constructor) {

            if (typeof(constructor) == 'object') {//已经是日期类型
                var datetime = constructor;
            }
            else {
                var datetime = constructor ? new Date(constructor) : new Date();
            }

            format = format || 'Y-m-d H:i:s';

            var o = {
                'Y': datetime.getFullYear(),
                'm': datetime.getMonth() + 1,
                'd': datetime.getDate(),
                'H': datetime.getHours(),
                'i': datetime.getMinutes(),
                's': datetime.getSeconds()
            };

            for (var i in o) {
                _s = i == 'Y' ? o[i] : str_pad(o[i], 2, '0');//不为年，补0
                format = format.replace(new RegExp(i, 'g'), _s);
            }

            return format;
        }

        function htmlspecialchars(str) {
            return str.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, '&#39;');
        }

        function refreshOnline(users) {
            var html = '';
            html += '<ul><li id="' + username + '" style="color: red">' + username + '</li>';

            $.each(users, function(index, user) {
                html += user != username ? '<li id="' + user + '">' + user + '</li>' : '';
            });

            html += '</ul>';
            online.html(html);
        }

        function createSocket() {
            socket = io.connect('http://chat.mrmsl.com:3000');
            socket.on('connect', function() {
                $('<p style="color: gray"><em>已经连接服务器</em></p>').appendTo(div);
                $('#login').remove();
                login(username);
                this.emit('afterconnected', username);
            }).on('user connected', function(username) {
                login(username);
            }).on('afterdisconnect', function(username) {
                logout(username);
            }).on('user list', refreshOnline).on('public message', function(data) {
                $('<p><b>' + data.username + '</b> ' + date(date.date) + '<br /><em style="color: gray">' + htmlspecialchars(data.msg) + '</em></p>').appendTo(div);
                scroll();
            });

        }

        $(function() {
            div = $('#msg'), input = $('#content'), online = $('#online');

            $('#btn-connect').click(function() {
                var input = $('#username');
                username = $.trim(input.val());

                if (!username) {
                    input.focus();
                    return;
                }

                $('<p style="color: gray"><em>正在连接服务器，请稍后...</em></p>').appendTo(div);
                createSocket();
            });

            $('#btn-submit').click(function() {
                var content = $.trim(input.val());

                if (!content) {
                    return;
                }

                input.val('');

                socket.emit('message', {
                    msg: content,
                    date: new Date(),
                    username: username
                });
            });
        });
    </script>
</head>
<body>
    <p id="login"><input type="text" id="username"> <input type="button" id="btn-connect" value="连接" /></p>
    <div id="online" style="float: right"></div>
    <div id="msg" style="height: 300px; overflow: auto;"></div>
    <p>
        <textarea cols="80" rows="5" id="content"></textarea>
    </p>
    <p><input type="button" id="btn-submit" value="提交" /></p>
</body>
</html>